from heap.class_klass import HeapObject
from insts.inst import NoOperandInstruction
from jthread.frame import JFrame
from jthread.thread import JThread

# 在当前线程的堆栈帧中查找并跳转到异常处理器的方法
def findAndGotoExceptionHandler(t:JThread, ex:HeapObject):
    while True:
        frame:JFrame =  t.topFrame()
        pc = frame.getNextPc()-1
        handlerPc = frame.getJMethod().findExceptionHandler(ex.get_class().getName(),pc)
        if handlerPc >0:
            stack = frame.getOperandStack()
            stack.clear()
            stack.pushRef(ex)
            frame.setNextPc(handlerPc)
            return True
        t.popFrame()
        if t.isEmpty():
            break
    return False


# ATHROW指令类，继承自NoOperandInstruction类
class ATHROW(NoOperandInstruction):

    # 执行指令的方法
    def execute(self, frame):
        ex=frame.getOperandStack().popRef()
        if ex is None:
            raise Exception("NullPointerException")
        t = frame.getJThread()
        if findAndGotoExceptionHandler(t, ex):
            pass
